<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>行情信息 - OKX 数据展示</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f4f7fa;
            font-family: Arial, sans-serif;
        }
        .navbar {
            background-color: #0c2461;
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #0c2461;
            color: white;
            border-radius: 10px 10px 0 0;
            padding: 15px;
            font-weight: bold;
        }
        .price-card {
            text-align: center;
            padding: 30px 0;
        }
        .price-value {
            font-size: 48px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .price-label {
            font-size: 14px;
            color: #6c757d;
        }
        .positive {
            color: #2ed573;
        }
        .negative {
            color: #ff4757;
        }
        .details-card {
            border-radius: 10px;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        .details-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .details-value {
            font-size: 24px;
            font-weight: 500;
        }
        .details-row {
            margin-bottom: 15px;
        }
        .badge-custom {
            font-size: 16px;
            padding: 8px 12px;
        }
        .refreshed-time {
            font-size: 12px;
            color: #6c757d;
            text-align: right;
            margin-top: 5px;
        }
        .btn-place-order {
            margin-top: 15px;
        }
        .product-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .product-title {
            font-size: 24px;
            font-weight: bold;
            margin: 0;
        }
        .price-change-container {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 10px 15px;
            display: inline-block;
            margin: 10px 0;
        }
        .action-btn {
            border-radius: 8px;
            padding: 10px 20px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .market-data-section {
            margin-top: 30px;
        }
        .market-data-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }
    </style>
</head>
<body>
    <!-- 引入导航栏片段 -->
    <div th:replace="fragments/navbar :: navbar"></div>

    <div class="container">
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>行情信息</span>
                <div>
                    <span id="connection-status" class="badge bg-secondary me-2" title="WebSocket连接状态">连接中...</span>
                    <select id="account-select" class="form-select form-select-sm d-inline-block" style="width: 200px;" aria-label="选择产品">
                        <option value="">-- 选择产品 --</option>
                        <option th:each="account : ${accounts}"
                                th:value="${account.instId}"
                                th:text="${account.accountName + ' (' + account.instId + ')'}"
                                th:selected="${account.instId == instId}">
                        </option>
                    </select>
                    <span class="mx-2">或</span>
                    <input type="text" id="instId-input" class="form-control form-control-sm d-inline-block" th:value="${instId}" style="width: 150px;">
                    <button id="change-instId-btn" class="btn btn-sm btn-outline-light">切换</button>
                </div>
            </div>
            <div class="card-body">
                <div class="alert alert-info mb-4">
                    <strong>产品行情详情</strong>：<span th:text="${pageDescription ?: '本页面显示产品管理表中已配置产品的详细行情信息，支持下单交易'}">本页面显示产品管理表中已配置产品的详细行情信息，支持下单交易。</span> 如需查看更多产品，请前往<a href="/all-markets" class="alert-link">所有行情</a>页面。
                </div>
                
                <div class="row">
                    <div class="col-md-12 mb-4">
                        <div class="card price-card">
                            <div class="card-body">
                                <h5 class="card-title" id="product-title">加载中...</h5>
                                <div class="price-value" id="last-price">--</div>
                                <div class="d-flex justify-content-center">
                                    <div class="price-change">
                                        24小时涨跌: <span id="price-change-value">--</span>
                                        (<span id="price-change-percent">--</span>)
                                    </div>
                                </div>
                                <div class="btn-place-order">
                                    <button id="placeOrderBtn" class="btn btn-success btn-lg" data-bs-toggle="modal" data-bs-target="#placeOrderModal">下单</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="card details-card">
                            <div class="card-body">
                                <div class="details-title">买一</div>
                                <div class="details-value text-success" id="bid-price">--</div>
                                <div id="bid-size">--</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="card details-card">
                            <div class="card-body">
                                <div class="details-title">卖一</div>
                                <div class="details-value text-danger" id="ask-price">--</div>
                                <div id="ask-size">--</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card details-card">
                            <div class="card-body">
                                <div class="details-title">24h最高</div>
                                <div class="details-value" id="high24h">--</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card details-card">
                            <div class="card-body">
                                <div class="details-title">24h最低</div>
                                <div class="details-value" id="low24h">--</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card details-card">
                            <div class="card-body">
                                <div class="details-title">24h成交量</div>
                                <div class="details-value" id="vol24h">--</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="refreshed-time">
                    最后更新时间: <span id="last-update-time">-</span>
                </div>
            </div>
        </div>
    </div>

    <footer class="container mt-5">
        <hr>
        <p class="text-center text-muted">&copy; 2023 OKX 数据展示系统</p>
    </footer>

    <!-- 下单模态框 -->
    <div class="modal fade" id="placeOrderModal" tabindex="-1" aria-labelledby="placeOrderModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="placeOrderModalLabel">下单</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="orderForm">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="orderInstId" class="form-label">产品ID</label>
                                <input type="text" class="form-control" id="orderInstId" readonly>
                            </div>
                            <div class="col-md-6">
                                <label for="orderPrice" class="form-label">当前价格</label>
                                <input type="text" class="form-control" id="orderPrice" readonly>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="tdMode" class="form-label">交易模式</label>
                                <div class="btn-group w-100" role="group">
                                    <input type="radio" class="btn-check" name="tdMode" id="tdModeCross" value="cross" checked>
                                    <label class="btn btn-outline-primary" for="tdModeCross">全仓 (cross)</label>

                                    <input type="radio" class="btn-check" name="tdMode" id="tdModeIsolated" value="isolated">
                                    <label class="btn btn-outline-primary" for="tdModeIsolated">逐仓 (isolated)</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label for="leverage" class="form-label">杠杆倍数</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="leverage" name="leverage" 
                                           min="1" max="100" step="1" value="20">
                                    <span class="input-group-text">x</span>
                                </div>
                                <div class="form-text text-muted">杠杆范围: 1-100，只能是整数</div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">开仓方向</label>
                                <div class="btn-group w-100" role="group">
                                    <input type="radio" class="btn-check" name="orderDirection" id="orderDirectionLong" value="long" checked>
                                    <label class="btn btn-outline-success" for="orderDirectionLong">开多 (long)</label>

                                    <input type="radio" class="btn-check" name="orderDirection" id="orderDirectionShort" value="short">
                                    <label class="btn btn-outline-danger" for="orderDirectionShort">开空 (short)</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label for="orderAmount" class="form-label">下单金额</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="orderAmount" min="0" step="0.01" value="100">
                                    <span class="input-group-text">USDT</span>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="orderSize" class="form-label">委托数量（张数）</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="orderSize" min="1" value="1" readonly>
                                    <button class="btn btn-outline-secondary" type="button" id="calculateSizeBtn">计算</button>
                                </div>
                                <div class="form-text text-muted">前端计算仅供参考，实际委托数量将由后端根据最新价格计算</div>
                            </div>
                            <div class="col-md-6">
                                <label for="faceValue" class="form-label">面值</label>
                                <input type="number" class="form-control" id="faceValue" value="0.01" step="0.001">
                            </div>
                        </div>
                    </form>

                    <!-- 错误提示 -->
                    <div id="orderErrorAlert" class="alert alert-danger mt-3 d-none" role="alert">
                        下单失败，请检查参数后重试
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" id="submitOrderBtn" class="btn btn-primary">确认下单</button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <script th:src="@{/js/sockjs.min.js}"></script>
    <script th:src="@{/js/stomp.min.js}"></script>
    <script>
        // CSRF令牌处理
        const csrfToken = document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*\=\s*([^;]*).*$)|^.*$/, "$1");
        
        // 获取页面元素
        const connectionStatus = document.getElementById('connection-status');
        const productTitle = document.getElementById('product-title');
        const lastPrice = document.getElementById('last-price');
        const priceChangeValue = document.getElementById('price-change-value');
        const priceChangePercent = document.getElementById('price-change-percent');
        const bidPrice = document.getElementById('bid-price');
        const bidSize = document.getElementById('bid-size');
        const askPrice = document.getElementById('ask-price');
        const askSize = document.getElementById('ask-size');
        const high24h = document.getElementById('high24h');
        const low24h = document.getElementById('low24h');
        const vol24h = document.getElementById('vol24h');
        const lastUpdateTime = document.getElementById('last-update-time');
        const instIdInput = document.getElementById('instId-input');
        const changeInstIdBtn = document.getElementById('change-instId-btn');
        const accountSelect = document.getElementById('account-select');
        
        // WebSocket连接
        let stompClient = null;
        // 从URL获取instId参数，如果不存在则使用默认值
        const urlParams = new URLSearchParams(window.location.search);
        let currentInstId = urlParams.get('instId') || (accountSelect && accountSelect.value ? accountSelect.value : "BTC-USDT");
        let lastRequestedInstId = ''; // 记录最后请求的产品ID

        // 添加调试日志
        console.log('初始产品ID:', currentInstId);

        // 数字格式化工具
        const formatNumber = (num, decimals = 2) => {
            if (!num) return '--';
            return Number(num).toLocaleString('en-US', {
                minimumFractionDigits: decimals,
                maximumFractionDigits: decimals
            });
        };

        // 保存当前订阅
        let currentSubscription = null;

        // 订阅特定产品的ticker主题
        function subscribeToSpecificTicker(instId) {
            // 先取消之前的订阅
            if (currentSubscription) {
                console.log('取消之前的订阅');
                try {
                    currentSubscription.unsubscribe();
                } catch (e) {
                    console.error('取消订阅失败:', e);
                }
                currentSubscription = null;
            }

            if (stompClient && stompClient.connected) {
                console.log('订阅特定产品行情:', instId);
                // 订阅特定产品的主题
                currentSubscription = stompClient.subscribe(`/topic/ticker/${instId}`, function(message) {
                    try {
                        const ticker = JSON.parse(message.body);
                        console.log('收到特定产品行情:', ticker.instId);
                        updateTickerData(ticker);
                    } catch (e) {
                        console.error('解析特定产品行情失败:', e);
                    }
                });

                // 立即请求该产品数据
                requestTickerData(instId);
            }
        }

        // 请求行情数据
        function requestTickerData(specificInstId = null) {
            const instIdToRequest = specificInstId || currentInstId;

            if (stompClient !== null && stompClient.connected) {
                console.log('请求行情数据:', instIdToRequest);
                lastRequestedInstId = instIdToRequest; // 记录请求的产品ID

                // 强制清除UI，表明正在加载新数据
                productTitle.textContent = instIdToRequest + ' (加载中...)';
                lastPrice.textContent = '--';
                priceChangeValue.textContent = '--';
                priceChangePercent.textContent = '--';
                bidPrice.textContent = '--';
                bidSize.textContent = '--';
                askPrice.textContent = '--';
                askSize.textContent = '--';
                high24h.textContent = '--';
                low24h.textContent = '--';
                vol24h.textContent = '--';

                // 发送请求
                stompClient.send('/app/ticker', {}, JSON.stringify({
                    instId: instIdToRequest
                }));
            } else {
                console.warn('WebSocket未连接，使用HTTP获取数据');
                fetchTickerViaHttp(instIdToRequest);
            }
        }

        // 通过HTTP API获取行情数据
        function fetchTickerViaHttp(specificInstId = null) {
            const instIdToRequest = specificInstId || currentInstId;

            console.log('通过HTTP获取行情数据:', instIdToRequest);
            fetch('/api/v2/ticker?instId=' + instIdToRequest)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('HTTP响应错误: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('HTTP API获取行情数据成功:', data);
                    updateTickerData(data);
                })
                .catch(error => {
                    console.error('获取行情数据失败:', error);
                });
        }

        // 连接WebSocket
        function connect() {
            connectionStatus.textContent = '连接中...';
            connectionStatus.className = 'badge bg-secondary me-2';
            
            try {
                const socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);

                // 添加调试日志
                console.log('正在连接WebSocket...');

                // 配置stomp客户端，减少调试日志
                stompClient.debug = null; // 禁用调试日志
            
            stompClient.connect({}, function(frame) {
                connectionStatus.textContent = '已连接';
                connectionStatus.className = 'badge bg-success me-2';
                    console.log('WebSocket连接成功');

                    // 订阅通用行情主题
                    stompClient.subscribe('/topic/ticker', function(message) {
                        try {
                            const ticker = JSON.parse(message.body);
                            console.log('收到通用行情数据:', ticker.instId);

                            // 如果当前没有选择具体产品，则使用通用主题数据
                            if (!currentInstId || ticker.instId === currentInstId) {
                                updateTickerData(ticker);
                            }
                        } catch (e) {
                            console.error('解析行情数据失败:', e);
                        }
                    });

                    // 特定产品的主题订阅
                    if (currentInstId) {
                        subscribeToSpecificTicker(currentInstId);
                    } else if (accountSelect && accountSelect.value) {
                        // 如果有默认选择的产品，则订阅该产品
                        currentInstId = accountSelect.value;
                        subscribeToSpecificTicker(currentInstId);
                    } else {
                        // 否则请求默认产品的数据
                        requestTickerData();
                    }

                    // 重置连接状态
                    lastSuccessfulUpdate = new Date();

                }, function(error) {
                    connectionStatus.textContent = '连接失败';
                    connectionStatus.className = 'badge bg-danger me-2';
                    console.error('连接失败:', error);

                    // 通过HTTP API获取数据
                    fetchTickerViaHttp();

                    // 5秒后尝试重连
                    setTimeout(connect, 5000);
                });
            } catch (e) {
                console.error('WebSocket连接异常:', e);
                connectionStatus.textContent = '连接失败';
                connectionStatus.className = 'badge bg-danger me-2';

                // 通过HTTP API获取数据
                fetchTickerViaHttp();

                // 10秒后重新尝试连接
                setTimeout(connect, 10000);
            }
        }

        // 更新行情数据
        function updateTickerData(ticker) {
            if (!ticker) {
                console.warn('收到空的行情数据');
                return;
            }

            console.log('更新行情数据:', ticker.instId, '当前选择:', currentInstId);

            // 如果收到的数据与当前选择的产品ID不匹配，但是最后请求的是这个产品，那么更新当前产品ID
            if (lastRequestedInstId && ticker.instId !== currentInstId && ticker.instId === lastRequestedInstId) {
                console.log('更新当前产品ID为最后请求的产品:', lastRequestedInstId);
                currentInstId = lastRequestedInstId;
            }

            if (ticker.instId === currentInstId) {
                console.log('更新行情数据UI:', ticker.instId);
                // 从加载状态恢复
                if (productTitle.textContent.includes('加载中')) {
            productTitle.textContent = ticker.instId;
                }

                lastPrice.textContent = formatNumber(ticker.last, 4);

                // 计算24h涨跌幅
                const open24h = ticker.open24h;
                const last = ticker.last;
                const change = Number(last) - Number(open24h);
                const changePercent = (change / Number(open24h)) * 100;

                priceChangeValue.textContent = formatNumber(change, 4);
                priceChangePercent.textContent = formatNumber(changePercent, 2) + '%';

                if (change > 0) {
                    lastPrice.className = 'price-value positive';
                priceChangeValue.className = 'positive';
                priceChangePercent.className = 'positive';
                } else if (change < 0) {
                    lastPrice.className = 'price-value negative';
                priceChangeValue.className = 'negative';
                priceChangePercent.className = 'negative';
                } else {
                    lastPrice.className = 'price-value';
                    priceChangeValue.className = '';
                    priceChangePercent.className = '';
                }

                bidPrice.textContent = formatNumber(ticker.bidPx, 4);
                bidSize.textContent = formatNumber(ticker.bidSz, 4);
                askPrice.textContent = formatNumber(ticker.askPx, 4);
                askSize.textContent = formatNumber(ticker.askSz, 4);
                high24h.textContent = formatNumber(ticker.high24h, 4);
                low24h.textContent = formatNumber(ticker.low24h, 4);
                vol24h.textContent = formatNumber(ticker.vol24h, 4);

                // 每次数据更新时都强制更新最后更新时间，确保UI反映数据刷新
                updateLastUpdateTime();

                // 更新数据成功
                lastSuccessfulUpdate = new Date();
            } else {
                console.log('忽略非当前选择产品的行情数据:', ticker.instId);
            }
        }

        // 更新最后更新时间
        function updateLastUpdateTime() {
            const now = new Date();
            lastUpdateTime.textContent = now.toLocaleString();
            console.log('更新最后更新时间:', lastUpdateTime.textContent);
        }
        
        // 切换产品ID - 只在元素存在时添加事件
        if (changeInstIdBtn && instIdInput) {
        changeInstIdBtn.addEventListener('click', function() {
                const newInstId = instIdInput.value.trim();
            if (newInstId && newInstId !== currentInstId) {
                    console.log('切换产品ID:', newInstId);
                    currentInstId = newInstId;

                    // 立即请求新产品的数据
                    if (stompClient && stompClient.connected) {
                        requestTickerData();
                    } else {
                        fetchTickerViaHttp();
                    }

                    // 更新URL但不刷新页面
                    window.history.pushState({}, '', '/ticker?instId=' + encodeURIComponent(currentInstId));
                }
            });
        }

        // 账户下拉框改变
        if (accountSelect) {
            accountSelect.addEventListener('change', function() {
                const selectedInstId = accountSelect.value;
                if (selectedInstId) {
                    console.log('从下拉框选择产品ID:', selectedInstId);
                    // 如果instIdInput存在则更新其值
                    if (instIdInput) {
                        instIdInput.value = selectedInstId;
                    }

                    // 立即更新当前产品ID
                    currentInstId = selectedInstId;

                    // 显示正在加载的状态
                    productTitle.textContent = selectedInstId + ' (加载中...)';
                    lastPrice.textContent = '--';
                    priceChangeValue.textContent = '--';
                    priceChangePercent.textContent = '--';
                    bidPrice.textContent = '--';
                    bidSize.textContent = '--';
                    askPrice.textContent = '--';
                    askSize.textContent = '--';
                    high24h.textContent = '--';
                    low24h.textContent = '--';
                    vol24h.textContent = '--';

                    // 在选择产品时立即更新最后更新时间，显示数据正在刷新
                    updateLastUpdateTime();

                    // 重新订阅到新的产品主题
                    subscribeToSpecificTicker(selectedInstId);

                    // 更新URL但不刷新页面
                    window.history.pushState({}, '', '/ticker?instId=' + encodeURIComponent(currentInstId));

                    // 触发一次立即HTTP请求以确保数据更新
                    setTimeout(() => fetchTickerViaHttp(selectedInstId), 100);
                }
            });
        }

        // 记录最后成功更新的时间
        let lastSuccessfulUpdate = new Date();

        // 检测数据更新状态
        function checkDataUpdateStatus() {
            const now = new Date();
            const elapsedSinceLastUpdate = now - lastSuccessfulUpdate;

            // 如果超过10秒没有更新，尝试重新获取数据
            if (elapsedSinceLastUpdate > 10000) {
                console.warn('数据超过10秒未更新，尝试重新获取');

                // 显示数据可能不是最新的提示
                const outdatedTag = ' (数据可能不是最新)';
                if (productTitle.textContent && !productTitle.textContent.includes(outdatedTag)) {
                    productTitle.textContent = productTitle.textContent + outdatedTag;
                }

                // 尝试重新连接和获取数据
                if (!stompClient || !stompClient.connected) {
                    console.log('WebSocket未连接，尝试重新连接');
                    connect();
                } else {
                    console.log('重新请求数据');
                    requestTickerData();
                }

                // 同时通过HTTP获取
                fetchTickerViaHttp();
            }
        }

        // 每5秒检查一次数据更新状态
        setInterval(checkDataUpdateStatus, 5000);

        // 页面加载完成时连接WebSocket
        document.addEventListener('DOMContentLoaded', function() {
            connect();

            // 初始化
            lastSuccessfulUpdate = new Date();

            // 如果URL中没有instId但是有默认选项，自动选择默认选项
            if (!urlParams.has('instId') && accountSelect && accountSelect.options.length > 1) {
                // 选择第一个非空选项
                for (let i = 0; i < accountSelect.options.length; i++) {
                    if (accountSelect.options[i].value) {
                        accountSelect.selectedIndex = i;
                        // 手动触发change事件
                        accountSelect.dispatchEvent(new Event('change'));
                        break;
                    }
                }
            }
        });

        // 下单相关代码
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化下单模态框
            const placeOrderModal = document.getElementById('placeOrderModal');
            if (placeOrderModal) {
                placeOrderModal.addEventListener('show.bs.modal', function (event) {
                    // 设置产品ID和价格
                    document.getElementById('orderInstId').value = currentInstId;
                    // 直接从lastPrice元素获取价格，不再需要lastPrice输入框
                    const currentPrice = document.getElementById('last-price').textContent.replace(/,/g, '');
                    document.getElementById('orderPrice').value = currentPrice;
                    
                    // 从账户配置中获取面值（如果有）
                    fetchFaceValue(currentInstId);
                    
                    // 小延迟后自动计算订单大小
                    setTimeout(() => {
                        calculateOrderSize();
                    }, 300);
                });

                // 添加下单按钮事件
                document.getElementById('submitOrderBtn').addEventListener('click', placeOrder);

                // 添加计算张数按钮事件
                document.getElementById('calculateSizeBtn').addEventListener('click', calculateOrderSize);

                // 当金额、杠杆或面值变化时，自动计算张数
                ['orderAmount', 'leverage', 'faceValue'].forEach(id => {
                    document.getElementById(id).addEventListener('change', calculateOrderSize);
                    document.getElementById(id).addEventListener('input', calculateOrderSize);
                });
                
                // 添加杠杆输入验证
                const leverageInput = document.getElementById('leverage');
                leverageInput.addEventListener('input', function() {
                    // 移除非数字字符
                    this.value = this.value.replace(/[^0-9]/g, '');
                    
                    // 确保是整数且在1-100范围内
                    let value = parseInt(this.value);
                    
                    // 如果为空或NaN，不做处理
                    if (this.value === '' || isNaN(value)) {
                        return;
                    }
                    
                    // 限制最小值为1
                    if (value < 1) {
                        this.value = 1;
                    }
                    
                    // 限制最大值为100
                    if (value > 100) {
                        this.value = 100;
                    }
                });
                
                // 失去焦点时确保有默认值
                leverageInput.addEventListener('blur', function() {
                    if (this.value === '' || isNaN(parseInt(this.value))) {
                        this.value = 20; // 默认杠杆
                    }
                });
            }
        });

        // 计算订单张数
        function calculateOrderSize() {
            const amount = parseFloat(document.getElementById('orderAmount').value) || 0;
            const leverage = parseFloat(document.getElementById('leverage').value) || 20;
            const price = parseFloat(document.getElementById('orderPrice').value.replace(/,/g, '')) || 0;
            const faceValue = parseFloat(document.getElementById('faceValue').value) || 0.01;
            
            // 显示计算中状态
            const calculateBtn = document.getElementById('calculateSizeBtn');
            const originalBtnText = calculateBtn.textContent;
            calculateBtn.disabled = true;
            
            // 检查参数
            if (!amount || !leverage || !price || !faceValue) {
                document.getElementById('orderSize').value = 1;
                calculateBtn.disabled = false;
                calculateBtn.textContent = originalBtnText;
                showOrderError('请输入有效的金额、杠杆倍数和面值');
                return;
            }
            
            try {
                // 张数 = 保证金*杠杆倍数 / (面值*价格)
                let size = (amount * leverage) / (faceValue * price);
                
                // 取整，确保是整数，符合交易所lot size要求
                size = size.toFixed(2);
                
                // 确保至少为1
                if (size < 1) {
                    size = 1;
                }
                
                // 设置计算结果
                document.getElementById('orderSize').value = size;
                
                // 恢复按钮状态
                calculateBtn.disabled = false;
                calculateBtn.textContent = originalBtnText;
                
                // 隐藏错误提示
                hideOrderError();
                
                console.log('前端计算张数结果(仅供参考):', size, '参数:', {amount, leverage, price, faceValue});
                
            } catch (error) {
                // 恢复按钮状态
                calculateBtn.disabled = false;
                calculateBtn.textContent = originalBtnText;
                
                // 显示错误
                document.getElementById('orderSize').value = 1;
                console.error('计算订单大小失败:', error);
                showOrderError('计算失败: ' + error.message);
            }
        }

        // 执行下单
        function placeOrder() {
            // 获取表单数据
            const instId = document.getElementById('orderInstId').value;
            const tdMode = document.querySelector('input[name="tdMode"]:checked').value;
            const posSide = document.querySelector('input[name="orderDirection"]:checked').value;
            const sz = document.getElementById('orderSize').value;
            const amount = document.getElementById('orderAmount').value;
            const leverage = document.getElementById('leverage').value;

            // 根据持仓方向确定买卖方向
            let side;
            if (posSide === 'long') {
                side = 'buy';  // 开多需要买入
            } else {
                side = 'sell'; // 开空需要卖出
            }

            // 参数校验
            if (!instId || !tdMode || !side || !posSide || !sz || sz <= 0) {
                showOrderError('请填写完整的下单信息');
                return;
            }

            // 构建请求参数
            const params = new URLSearchParams();
            params.append('instId', instId);
            params.append('tdMode', tdMode);
            params.append('side', side);
            params.append('posSide', posSide);
            params.append('sz', sz);
            params.append('leverage', leverage);
            // 添加金额参数用于后端计算
            if (amount) {
                params.append('amount', amount);
            }

            // 显示加载状态
            const submitBtn = document.getElementById('submitOrderBtn');
            const originalText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 下单中...';

            // 隐藏错误提示
            hideOrderError();

            // 发送请求
            fetch('/api/v2/place-order', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-XSRF-TOKEN': csrfToken
                },
                body: params,
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(result => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;

                if (result.code === 0||result.code === '0') {
                    // 下单成功，关闭模态框
                    alert('下单成功');
                    bootstrap.Modal.getInstance(document.getElementById('placeOrderModal')).hide();
                } else {
                    // 下单失败，显示错误信息
                    showOrderError(result.msg || '下单失败，请稍后重试');
                }
            })
            .catch(error => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;

                console.error('下单失败:', error);
                showOrderError('下单请求失败: ' + error.message);
            });
        }

        // 显示下单错误提示
        function showOrderError(message) {
            const errorAlert = document.getElementById('orderErrorAlert');
            errorAlert.textContent = message;
            errorAlert.classList.remove('d-none');
        }

        // 隐藏下单错误提示
        function hideOrderError() {
            const errorAlert = document.getElementById('orderErrorAlert');
            errorAlert.classList.add('d-none');
        }

        // 获取产品面值
        function fetchFaceValue(instId) {
            if (!instId) return;
            
            // 默认面值
            let faceValue = 0.01;
            
            // 尝试从后端获取产品配置
            fetch(`/api/v2/account?instId=${encodeURIComponent(instId)}`)
                .then(response => response.json())
                .then(account => {
                    if (account && account.faceValue) {
                        faceValue = account.faceValue;
                    }
                    document.getElementById('faceValue').value = faceValue;
                    // 获取面值后自动计算张数
                    calculateOrderSize();
                })
                .catch(error => {
                    console.warn('获取产品面值失败，使用默认值:', error);
                    document.getElementById('faceValue').value = faceValue;
                });
        }
    </script>
</body>
</html> 
